import { useRequest } from 'ahooks';
import { Flex } from 'antd';
import { memo, useCallback, useEffect } from 'react';

import { useBarterStyles } from '../styles.tsx';
import { getMetadataFromOffers } from '../utils.ts';

import { BarterOffersCard } from './BarterOffersCard/BarterOffersCard.tsx';

import type { Offer, OfferType } from '../../../../../types.ts';
import type { FC } from 'react';

interface IBarterOffersProps {
    offers: Offer[],
    type: OfferType,
    shouldBeUpdate?: boolean;
    openModal: (w1: string, w2: string, initiator: boolean) => void;
}

/*todo: shouldBeUpdate depends of cachesum*/
export const BarterOffer:FC<IBarterOffersProps> = memo(({
    offers, 
    type,
    shouldBeUpdate = false,
    openModal,
}) => {

    const { styles } = useBarterStyles();
 
    const getMetadataOfOffer = useCallback(async () => {
       
        return await getMetadataFromOffers(offers);

    },  [offers]);

    const { data, loading, run } = useRequest(getMetadataOfOffer, { cacheKey: type, manual: true });

    useEffect(() => {
        if (!data || shouldBeUpdate) {
            run();
        }
    }, [shouldBeUpdate, run, data]);

    return (
        <Flex wrap gap={16} className={styles.barterOfferWrapper}>
            {
                (loading && !data )
                    ? <div>Загрузка...</div>
                    : data?.map(([key, value]) => (
                        <BarterOffersCard
                            key={key}
                            offerId={key}
                            listOfSuggestedNFTs={value.offersList.suggested}
                            listOfDesiredNFTs={value.offersList.desired}
                            isOutgoing={type === 'outgoing'}
                            openModal={() => openModal(value.initiatorAddress, value.receiverAddress, type === 'outgoing')}
                        />
                    ))
            }

        </Flex>
    );
});